<style scoped>
.ivu-number-info-subTitle {
    font-weight: bold;
}

.ivu-number-info-subTitle,
.ivu-number-info-value {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    word-break: break-all;
}

.ivu-number-info-subTotal,
.ivu-number-info-total {
    display: inline-block;
    height: 32px;
    line-height: 32px;
}

.ivu-number-info-total {
    margin-right: 32px;
    color: #515a6e;
    font-size: 24px;
}

.ivu-number-info-subTotal {
    margin-right: 0;
    vertical-align: top;
    font-size: 14px;
    color: #808695;
}

.ivu-trend {
    display: inline-block;
}

.ivu-trend-text {
    vertical-align: middle;
}

.ivu-trend-flag {
    color: #19be6b;
}

.ivu-page-header-title {
    display: inline-block;
    color: #17233d;
    font-weight: 500;
    font-size: 20px;
}

.ivu-description-term {
    display: table-cell;
    padding-bottom: 16px;
    line-height: 20px;
}

.ivu-description-detail {
    width: 100%;
    color: #515a6e;
}
</style>
<template>
    <div>
        <div class="ivu-mt">
            <el-card :bordered="false">
                <p class="card-title">
                    {{$t('message.term.order')}}
                </p>
                <el-divider dashed />
                <div class="ivu-page-header-main">
                    <div class="ivu-page-header-row">
                        <!---->
                        <div class="ivu-page-header-title">
                            <div>订单号：{{orderSN}}</div>
                        </div>
                        <!---->
                    </div>
                    <div>
                        <div class="ivu-description-term">创建时间：{{gmtCreated}}</div>
                    </div>
                </div>
                <el-divider dashed />
                <el-table :columns="columnsDefinition" :data="dataList"></el-table>
                <el-divider dashed />
                <div class="ivu-number-info">
                    <div class="ivu-number-info-subTitle">使用优惠券</div>
                    <div class="ivu-number-info-value" style="margin-top: 8px;">
                        {{orderDiscountName}}
                    </div>
                </div>
                <el-divider dashed />
                <div class="ivu-number-info">
                    <!---->
                    <div class="ivu-number-info-subTitle">总价(元)</div>
                    <div class="ivu-number-info-value" style="margin-top: 8px;">
                        <span class="ivu-number-info-total">{{totalPrice}}</span>
                        <span class="ivu-number-info-subTotal">
                            <div class="ivu-trend ivu-trend-down ivu-trend-colorful">
                                <span class="ivu-trend-text">{{priceDown}}</span>
                                <i class="ivu-trend-flag ivu-icon ivu-icon-md-arrow-dropdown"></i>
                            </div>
                        </span>
                    </div>
                </div>
                <div v-if="cancelButtonSwitch">
                    <el-divider dashed />
                    <div class="ivu-number-info">
                        <div class="ivu-number-info-subTitle">扫码支付</div>
                        <div class="ivu-number-info-value" style="margin-top: 8px;">
                            <div class="qrcode" ref="qrcodeContainer"></div>
                        </div>
                    </div>
                    <el-divider dashed />
                    <div style=" margin-top: 20px">
                        <el-button @click="backStep()">取消订单</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>
<script>
import { API } from '@/customized/http/api';
import QRCode from 'qrcodejs2'

export default {
    /*从父路由注入父路由页面的函数*/
    inject: ['next', 'back'],
    components: {

    },
    data() {
        return {
            timer: '',
            columnsDefinition: [{
                    title: '文件名',
                    key: 'goods_name',
                    ellipsis: true,
                    tooltip: true
                },
                {
                    title: '原价格(元)',
                    key: 'goods_price',
                    width: 120,
                    align: 'right'
                },
                {
                    title: '优惠',
                    key: 'discountName',
                    width: 120
                },
                {
                    title: '价格(元)',
                    key: 'finalPrice',
                    width: 100,
                    align: 'right'
                }
            ],
            dataList: [],
            totalPrice: 0,
            priceDown: 0,
            gmtCreated: "",
            orderDiscountName: "无",
            orderDetailSnapshot: "",
            cancelButtonSwitch: true
        }
    },
    computed: {
        orderSN() {
            return this.$route.params.orderSN;
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.loadDocList();
        });
    },
    beforeDestroy() {
        /* 记得销毁 */
        console.log("clearInterval(this.timer);");
        clearInterval(this.timer);
    },
    methods: {
        backStep() {
            this.$Modal.confirm({
                title: '确定回退么?',
                content: '<p>回退将取消此订单</p>',
                onOk: () => {
                    let postJson = this.orderDetailSnapshot;
                    API.cancelOrder({ formData: JSON.stringify(postJson) })
                        .then((response) => {
                            this.$store.commit('saveOrder', "");
                            this.back(this.$route.name);
                        }).catch((error) => {
                            console.log(error);
                        });
                }
            });
        },
        loadDocList() {
            /*let docSelectedForOrder = this.$store.getters.docSelectedForOrder;
            this.dataList = docSelectedForOrder;*/

            API.orderDetail({ sn: this.orderSN })
                .then((response) => {
                    let orderDetail = response.data;

                    this.gmtCreated = orderDetail.order.gmt_created;
                    this.dataList = orderDetail.orderItems;
                    this.calTotalPrice(this.dataList);

                    let orderDiscount = orderDetail.orderDiscount;
                    if (!!orderDiscount) {
                        this.orderDiscountName = orderDiscount.discount_name;
                    }

                    this.totalPrice = orderDetail.totalPrice;
                    this.priceDown = orderDetail.priceDown;

                    this.orderDetailSnapshot = orderDetail.orderDetailSnapshot;
                    this.showQRCode();
                }).catch((error) => {
                    console.log(error);
                });
        },
        /*确认哪些文件成为订单内的文件*/
        onDocSelectChange(selection) {

        },
        calTotalPrice(dataList) {
            let custormerDiscount = this.$store.getters.custormerDiscount;

            let newTotal = 0;
            let oldTotal = 0;
            dataList.map(item => {
                newTotal += item.finalPrice * 100;
                oldTotal += item.price * 100;
            })
            this.totalPrice = Math.floor(parseFloat(newTotal)) / 100;
            this.priceDown = Math.floor(parseFloat(oldTotal - newTotal)) / 100;
        },
        /**
         * 从服务端获取支付链接，在前端将链接变成二维码显示在页面上
         */
        showQRCode() {
            API.wxQrPay({
                sn: this.orderSN,
                pay_version: this.orderDetailSnapshot.paySnapshot.version,
                order_version: this.orderDetailSnapshot.orderSnapshot.version
            }).then((response) => {
                let bizpayurl = response.data;
                if (!bizpayurl) {
                    this.cancelButtonSwitch = false;
                    this.checkPayment();
                    return;
                }

                var qrcode = new QRCode(this.$refs.qrcodeContainer, {
                    text: bizpayurl,
                    width: 191,
                    height: 191,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H
                });

                /* 启用一个定时器，定时保存所输入的值 3秒*/
                this.timer = setInterval(this.checkPayment, 3000);
            }).catch((error) => {
                console.log(error);
            });
        },
        checkPayment() {
            API.havePaid({ sn: this.orderSN })
                .then((response) => {
                    let havePaid = response.data;
                    if (havePaid) {
                        this.cancelButtonSwitch = false;
                        //this.next(this.$route.name, { orderSN: this.orderSN }); 没有下一步了
                        this.sendMail();
                    }
                }).catch((error) => {
                    console.log(error);
                });
        },
        sendMail() {
            API.deliver({ sn: this.orderSN })
                .then((response) => {
                    let result = response.data;
                    this.$router.push({
                        name: `success`,
                        params: {
                            desc: '发送文档成功，请您到邮箱查收',
                            extra: '如果您的邮箱没有接收到邮件，请稍等片刻，有任何疑问可联系客服'
                        }
                    })
                }).catch((error) => {
                    console.log(error);
                });
        },
    }
}
</script>